﻿/*请求loading控制*/

var filepreview = angular.module('filepreview', ['Common', 'dropdownApp', 'loadModule']);
/*******************文件预览指令**********************/
filepreview.directive('filepre', ['$document', 'RequestTrainService', 'sysUserInfo',function ($document, RTS,sysUserInfo) {
    return {
        scope: {
            isdata: '=isdata'
        },
        //        transclude: true,
        //        replace: true,
        templateUrl: "/system/directive/train/filepreview.html",
        restrict: 'ECA', // E = Element, A = Attribute, C = Class, M = Comment
        link: function ($scope, el, attr) {
            
            if($scope.isdata.data!=undefined&&$scope.isdata.data.fileurlonly!=null&&$scope.isdata.data.fileurlonly.length>0){
                if($scope.isdata.data.fileurlonly.indexOf("?")==-1){
                    $scope.isdata.data.fileurlonly= $scope.isdata.data.fileurlonly+"?userid="+sysUserInfo.getuserinfo().user_ID+"&orgid="+sysUserInfo.getuserinfo().organization_ID;
                    $scope.isdata.data.filepreview= $scope.isdata.data.filepreview+"?userid="+sysUserInfo.getuserinfo().user_ID+"&orgid="+sysUserInfo.getuserinfo().organization_ID;
                }else{
                    $scope.isdata.data.fileurlonly= $scope.isdata.data.fileurlonly+"&userid="+sysUserInfo.getuserinfo().user_ID+"&orgid="+sysUserInfo.getuserinfo().organization_ID;
                    $scope.isdata.data.filepreview= $scope.isdata.data.filepreview+"&userid="+sysUserInfo.getuserinfo().user_ID+"&orgid="+sysUserInfo.getuserinfo().organization_ID;
                }
            }

            $scope.getpdfUrl = function (txt) {
                if (txt == "" || txt == undefined) {
                    return "";
                } else {
                    txt+="?v"+new Date();
                    if(txt.indexOf("?")==-1){
                        txt+="?v"+new Date();
                    }else{
                        txt+="&v"+new Date();
                    }
                    return commonFileUrl+"/resources/pdf2/officeshow/web/viewer.html?file=" + base64encode(encodeURI(txt));
                }
            }
            // ckt
            $scope.ckthide = function(otype){
                if("ckt|scrom".indexOf(otype.toLowerCase()) >= 0){
                    return true
                }
                return false
            
            }
            // txt 
            $scope.txthide = function (otype) {
                if ("txt|js".indexOf(otype.toLowerCase()) >= 0) {
                    return true;
                }
                return false;
            }
            // 视频
            $scope.videohide = function (otype) {
                if ("mp4|wmv".indexOf(otype.toLowerCase()) >= 0) {
                    return true;
                }
                return false;
            }
            $scope.mp3hide = function (otype) {
                if ("mp3".indexOf(otype.toLowerCase()) >= 0) {
                    return true;
                }
                return false;
            }
            // pdf
            $scope.pdfhide = function (otype) {
                if ("pdf|doc|docx|xls|xlsx|ppt|pptx".indexOf(otype.toLowerCase()) >= 0) {
                    return true;
                }
                return false;
            }
            // 图片
            $scope.imghide = function (otype) {
                if ("png|jpeg|img|jpg|gif".indexOf(otype.toLowerCase()) >= 0) {
                    return true;
                }
                return false;
            }
            // 其他 $scope.txthide(otype) ||
            $scope.otherhide = function (otype) {
                if ($scope.videohide(otype) || $scope.mp3hide(otype) || $scope.pdfhide(otype) || $scope.imghide(otype) ||  $scope.ckthide(otype)) {
                    return false;
                }
                return true;
            }

            $scope.$watch('isdata.divhide', function (newValue, oldValue, scope) {
                //兼容下拉列表指令
                if ($scope.isdata.divhide) {
                    if ($scope.pdfhide($scope.isdata.data.fileType)) {
                        $scope.docstyle = { "overflow-y": "auto", "height": (document.documentElement.clientHeight - 145) + "px", "overflow-x": "hidden" };
                    } else {
                        $scope.docstyle = { "overflow-y": "auto", "max-height": (document.documentElement.clientHeight - 145) + "px", "overflow-x": "hidden" };
                    }
                } else {
                    $scope.docstyle = { "overflow-y": "auto", "max-height": (document.documentElement.clientHeight - 145) + "px", "overflow-x": "hidden" };
                }
                //                console.log($scope.docstyle);
            }, true);

            // 下载
            $scope.downpaly = function (item, index) {

//                    RTS.downloadfile({ id: item.upId, type: index, fileType: item.fileType }).then(function (data) {
//                        if (data.errorcode == 0) {
//                            if (item.fileType != "wxt" && item.fileType != "urls" && item.fileType != "ques") {
                                //请求文件服务器
                                window.open(RTS.filedown("?userid=" + item.upUserId + "&fileurlonly=" + encodeURI(encodeURI(item.fileurlonly)) + "&fileName=" + item.upId + "." + item.fileType + "&type=" + index));
//                            }
//                        } else {
//                            Msg.error("下载失败");
//                        }
//                    }, function callback() {
//                        Msg.error("请求数据有误");
//                    });
            }
            // 关闭
            $scope.ishidefun = function () {
                $scope.isdata.divhide = false;
            }
            // 隐藏
            function documentKeydown(event) {
                if (event.keyCode === 27) {
                    $scope.$apply(function () {
                        $scope.ishidefun();
                    });
                }
            }
            $document.on('keydown', documentKeydown);
            $scope.$on('$destroy', function () {
                $document.off('keydown', documentKeydown);
            });
            //  文件地址配置
            $scope.pathisdata={
               isShow:false
            }            
            //  打开获取文件地址
            $scope.openPath = function(item){                
                $scope.pathisdata.name =item.fileName;
                $scope.pathisdata.path = item.fileurlonly;
                $scope.pathisdata.isShow = true;
            } 
      $scope.myBrowser=function(){
        var userAgent = navigator.userAgent; //取得浏览器的userAgent字符串
        var isOpera = userAgent.indexOf("Opera") > -1;
        if (isOpera) {
            return "Opera"
        }; //判断是否Opera浏览器
        if (userAgent.indexOf("Firefox") > -1) {
            return "FF";
        } //判断是否Firefox浏览器
        if (userAgent.indexOf("Chrome") > -1){
            return "Chrome";
        }
        if (userAgent.indexOf("Safari") > -1) {
            return "Safari";
        } //判断是否Safari浏览器
        if (userAgent.indexOf("compatible") > -1 && userAgent.indexOf("MSIE") > -1 && !isOpera) {
            return "IE";
        }; //判断是否IE浏览器
        if (userAgent.indexOf("Trident") > -1) {
            return "Edge";
        } //判断是否Edge浏览器
    }
 
    $scope.oDownLoad=function(item) {
        if ($scope.myBrowser()==="IE" || $scope.myBrowser()==="Edge"){
            var oPop = window.open(item.fileurlonly,"","width=1, height=1, top=5000, left=5000");
            for(; oPop.document.readyState != "complete"; )
            {
                if (oPop.document.readyState == "complete")break;
            }
            oPop.document.execCommand("SaveAs");
            oPop.close();
        }else{
            //!IE
            var odownLoad=document.getElementById("oDownLoad");
            odownLoad.href=item.fileurlonly;
            odownLoad.download="";
        }
           
    }
    }
    }
} ]);
/*******************文件预览指令**********************/
filepreview.directive('filepath', ['$document', 'RequestTrainService', 'sysUserInfo', 'Msg', 'MsgCon', 'RequestPopService', 'FileUploader', '$timeout', function ($document, RTS, sysUserInfo, Msg, MsgCon, RPS, FileUploader, $timeout) {
    return {
        scope: {
            isdata: '=isdata',            
        },
        templateUrl: "/system/directive/train/filepath.html",
        restrict: 'ECA',
        link: function ($scope, el, attr) {
         if($scope.isdata!=undefined&&$scope.isdata.path!=null&&$scope.isdata.path.length>0&&$scope.isdata.path.indexOf("userid")==-1){
            if($scope.isdata.path.indexOf("?")==-1){
                $scope.isdata.path= $scope.isdata.path+"?userid="+sysUserInfo.getuserinfo().user_ID+"&orgid="+sysUserInfo.getuserinfo().organization_ID;
            }else{
                $scope.isdata.path= $scope.isdata.path+"&userid="+sysUserInfo.getuserinfo().user_ID+"&orgid="+sysUserInfo.getuserinfo().organization_ID;
            }
            
         }
         $scope.closePath= function(){
                $scope.isdata.isShow = false;
            }
        }
}}]);
/*******************文件属性指令**********************/
filepreview.directive('fileattr', ['$document', 'RequestTrainService', 'sysUserInfo', 'Msg', 'MsgCon', 'RequestPopService', 'FileUploader', '$timeout', function ($document, RTS, sysUserInfo, Msg, MsgCon, RPS, FileUploader, $timeout) {
    return {
        scope: {
            isdata: '=isdata',
            onCopyfile: '&',
            onMovefile: '&',
            onDelkn: '&',
            onFilepreview: '&',
            onKnlist: '&'
        },
        templateUrl: "/system/directive/train/fileattr.html",
        restrict: 'ECA',
        link: function ($scope, el, attr) {

            //  文件地址配置
            $scope.pathisdata={
               isShow:false
            }            
            //  打开获取文件地址
            $scope.openPath = function(item,flag){                
                if(flag == 2){ // 子版本                    
                    $scope.pathisdata.name =item.Name+"."+item.Extended;
                    $scope.pathisdata.path = item.URL;  
                }else{                
                    $scope.pathisdata.name =item.fileName;
                    $scope.pathisdata.path = item.fileurlonly;                  
                }
                
                $scope.pathisdata.isShow = true;
            }            
            $scope.isbtnload = false;
            $scope.isbtnload2 = false;

            $scope.knbody = function () {
                // if ($scope.orglist.length >= 5) {
                return { "max-height": document.documentElement.clientHeight - 320 + "px" };
                // } else {
                //  return { "height": document.documentElement.clientHeight - 320 - ((5 - $scope.orglist.length) * 27) + "px" };
                // }
            }

            //更新主版本  、 上传新文件
            $scope.updateparantobj = function (newobj) {
                $scope.vid = newobj.Edition; //更新字表版本
                $scope.fileifno.fileType = newobj.Extended; // 更新版本类型
                $scope.fileifno.fileversion = newobj.Edition;   // 更新主表版本
                $scope.fileifno.filepath = newobj.URL;  // 同步主表的地址
                $scope.fileifno.updatetime = newobj.UploadDate; // 同步主表的更新时间
                $scope.fileifno.fileSize = newobj.Size; // 同步主表大小
            }

            $scope.mousePosition = function (ev) {
                if (!ev) {
                    ev = window.event;
                }

                if (ev.type != "click") {
                    return;
                }
                var width = 0;
                var height = 0;
                if (ev.pageX || ev.pageY) {//firefox、chrome等浏览器
                    if (document.documentElement.clientWidth - ev.pageX < 450) {
                        width = ev.pageX - (450 - (document.documentElement.clientWidth - ev.pageX)) - 20;
                    } else {
                        width = ev.pageX;
                    }
                    if (document.documentElement.clientHeight - ev.pageY < 480) {
                        height = ev.pageY - (480 - (document.documentElement.clientHeight - ev.pageY)) - 20;
                    } else {
                        height = ev.pageY;
                    }

                    return { "left": width + "px", "top": height + "px", "position": "fixed" };
                }

                return {// IE浏览器
                    "left": ev.clientX + document.body.scrollLeft - document.body.clientLeft,
                    "top": ev.clientY + document.body.scrollTop - document.body.clientTop
                };
            }

            $scope.copyfileattr = function () { $scope.onCopyfile(); $scope.ishidefun(); } //复制
            $scope.movefileattr = function () { $scope.onMovefile(); $scope.ishidefun(); } //移动
            $scope.delknattr = function () { $scope.onDelkn(); } //删除
            $scope.filepreviewattr = function () { $scope.onFilepreview(); $scope.ishidefun(); } //预览
            $scope.filelist = function () { $scope.onKnlist(); } //文件列表

            //文件属性详细信息
            $scope.fileifno = { "upId": "", "filestate": "0", "filepath": "http://wwww.xxx.com/111.mp4", "filetype": "1", "fileversion": "0", "filename": "文件名称", "username": "", "createdate": "", "fid": "", "filecover": "", "fileurl": "", "filesize": "", "orgid": "", "sel": "", "update": "", "userid": "", "taglist": [], "Share": "1" };
            //文件属性标签
            $scope.extend = { "oldtag": RTS.getOldTagList(), newtag: [] };
            //文件原名称
            var filename = "";

            $scope.$watch('isdata.divhide', function (newValue, oldValue, scope) {
                //                if ((newValue != "" && oldValue == "") || oldValue.upId != newValue.upId) {
                if ($scope.isdata.divhide) {
                    $scope.filepath1 = $scope.isdata.filepath;
                    $scope.fileifno = $scope.isdata.data;
                    filename = angular.copy($scope.fileifno.fileName);
                    $scope.extend = { "oldtag": RTS.getOldTagList(), newtag: [] };
                    //$scope.knList();
                    if ($scope.fileifno != "") {
                        $scope.gettaglistbyfid($scope.fileifno.upId);
                        $scope.getrole($scope.fileifno.upId);
                    }
                }
                //                }
            }, true);


            //根据文件ID查询对应的标签列表
            $scope.gettaglistbyfid = function (fid) {
                RTS.getfiletag({ fileid: fid, userid: sysUserInfo.getuserinfo().user_ID, orgid: sysUserInfo.getuserinfo().organization_ID }).then(function (kbdata) {
                    if (kbdata.errorcode == 0) {
                        $scope.extend.newtag = kbdata.datas;
                        //剔除已经选择的下拉项
                        if ($scope.extend.newtag.length > 0) {
                            for (var i = 0; i < $scope.extend.newtag.length; i++) {
                                $scope.extend.oldtag.splice($scope.getindex($scope.extend.newtag[i], $scope.extend.oldtag), 1);
                            }
                            //                            console.log($scope.extend.oldtag);
                        }
                    } else {
                        Msg.error("文件标签获取异常！");
                        $scope.extend.newtag = [];
                    }
                });
            }


            /*********************************权限选择器对应的数据********************************************************/

            $scope.ApiData = {
                style: "",
                windowModal: "1", //调用模式 1弹窗模式 2宽度大于450 3 宽度小于450
                ViceOrgOpen: false, //HtmlOrg弹框样式 关闭 选择器再次引用选择器样式
                ViceGroupOpen: false, //HtmlOrg弹框样式 关闭 选择器再次引用选择器样式
                ViceRoleOpen: false, //HtmlOrg弹框样式 关闭 选择器再次引用选择器样式
                ApiOpen: false, //为true时 页面打开选择器 false 关闭控制器
                menu: [//进入人员选择器的菜单         
                                 {"id": "Org" },
                                 { "id": "Group" },
                                { "id": "Role" },
                                { "id": "User" }
                             ],
                "ViceuserRoleList": [//传入的角色列表 再次点击 查询 双向绑定不能影响数据源

                            ],
                "ViceuserOrgList": [//传入的部门列表 再次点击 查询 双向绑定不能影响数据源

                            ],
                "ViceuserGroupList": [//传入的用户组 再次点击 查询 双向绑定不能影响数据源

                            ],
                "ViceuserUserList": [//传入的用户组 再次点击 查询 双向绑定不能影响数据源

                            ],
                userOrgList: [],
                userRoleList: [],
                userGroupList: [],
                UserList: [],
                searchType: []
            };

            //声明 新增权限数组
            $scope.addPersonList = [];
            //声明 删除权限数组
            $scope.delPersonList = [];

             $scope.qxList=[];
              $scope.$watch('ApiData.ApiOpen', function (newValue, oldValue, scope) {
                    //关闭状态
                    if(!$scope.ApiData.ApiOpen){
                        if($scope.ApiData.userOrgList.length>0){
                            $scope.ApiData.userOrgList.forEach(function(data,index){
                                var obj={ XID: data.organization_ID, XName: data.organization_Name, XType: 1, upid: $scope.fileifno.upId, sharetype: "0", shareid: sysUserInfo.getuserinfo().user_ID, shareName: sysUserInfo.getuserinfo().username };
                                $scope.qxList.push(obj);
                                $scope.addPersonList.push(obj);
                            });
                        }
                        if($scope.ApiData.userRoleList.length>0){
                            $scope.ApiData.userRoleList.forEach(function(data,index){
                                var obj={ XID: data.roles_ID, XName: data.roles_Name, XType: 2, upid: $scope.fileifno.upId, sharetype: "0", shareid: sysUserInfo.getuserinfo().user_ID, shareName: sysUserInfo.getuserinfo().username };
                                $scope.qxList.push(obj);
                                $scope.addPersonList.push(obj);
                            });
                        }
                        if($scope.ApiData.userGroupList.length>0){
                            $scope.ApiData.userGroupList.forEach(function(data,index){
                                var obj={ XID: data.userGroup_ID, XName: data.userGroup_Name, XType:3, upid: $scope.fileifno.upId, sharetype: "0", shareid: sysUserInfo.getuserinfo().user_ID, shareName: sysUserInfo.getuserinfo().username };
                                $scope.qxList.push(obj);
                                $scope.addPersonList.push(obj);
                            });
                        }
                        if($scope.ApiData.UserList.length>0){
                            $scope.ApiData.UserList.forEach(function(data,index){
                                 var obj={ XID: data.user_ID, XName: data.user_Name, XType:4, upid: $scope.fileifno.upId, sharetype: "0", shareid: sysUserInfo.getuserinfo().user_ID, shareName: sysUserInfo.getuserinfo().username };
                                $scope.qxList.push(obj);
                                $scope.addPersonList.push(obj);
                            });
                        }

                    }
                }, true);


            //获取文件对应的权限
            $scope.getrole = function (fileid) {
                RTS.getfileShare({ fileid: fileid, shareid: sysUserInfo.getuserinfo().user_ID, r: Math.random() }).then(function (data) {
                    if (data.errorcode == "0"&&data.datas.length >0) {
                        $scope.qxList=data.datas;
                        //这是老的数据
                        $scope.qxList.forEach(function(obj,index){
                            obj.old=1;
                        });
                    } else {
						$scope.qxList=[];
                        console.log("权限获取异常：" + data.errorcode);
                    }
                    
                });
            }
            //删除权限
            $scope.delFileQx=function(obj){
                $scope.qxList.forEach(function(data,index){
                    if(obj.XID==data.XID){
                        if(data.hasOwnProperty("old")){
                            delete data.obj;
                            $scope.delPersonList.push(data);
                        }
                         $scope.qxList.splice(index,1);
                    }
                });
            }

           
            //保存 修改文件属性
            $scope.upAttribute = function () {
                $scope.isbtnload = true;

                var checkCount=0;
                //查询共享的数量
                $scope.qxList.forEach(function(item,index){
                        checkCount++;
                });

                //选中数量大于0，有权限，是共享文件
                if (checkCount>0) {
                    $scope.fileifno.Shares = "0";
                } else {
                    $scope.fileifno.Shares = "1";
                }
                // 问答题处理
                //$scope.fileifno.fileTxt = JSON.stringify($scope.fileifno.fileTxt);
                 if(typeof $scope.fileifno.fileTxt!='string'){
                    $scope.fileifno.fileTxt = JSON.stringify($scope.fileifno.fileTxt);
                 }
                //$scope.GetRepeatList($scope.addPersonList)
                RTS.upfileinfo({ "attribute": $scope.fileifno, "extend": $scope.extend.newtag, "addqx": $scope.addPersonList, "delqx": $scope.delPersonList ,"userid":sysUserInfo.getuserinfo().user_ID }).then(function (data) {
                    $scope.isbtnload = false;
                    if (data.errorcode == 0) {
                        $scope.filelist();
                        $scope.ishidefun();
                        $scope.isdata.data = data.data;
                        Msg.success("保存成功！");
                    } else {
                        Msg.error("操作失败！");
                    }
                });
            }

            // 获取删除的索引 
            $scope.getindex = function (item, list) {
                var inde = -1;
                list.forEach(function (data, index, array) {
                    if (array[index].tagid == item.tagid) {
                        inde = index;
                    }
                });
                return inde;
            }

            //现在人员选择器
            $scope.openfind = function (event) {
                $scope.ApiData.ApiOpen = true;
                $scope.ApiData.userOrgList= [];
                $scope.ApiData.userRoleList=[];
                $scope.ApiData.userGroupList= [];
                $scope.ApiData.UserList=[];
                $scope.ApiData.style = $scope.mousePosition(event);
            }
            /*************************************************************************************************************/
            $scope.isshowhistory = false;   // 文件历史版本显示隐藏
            $scope.isshowlog = false;   // 文件日志查看显示隐藏
            $scope.docstyle = { "max-height": $document[0].body.clientHeight - 130 + "px" };

            //显示文件版本
            $scope.showhistory = function () {
                if ($scope.isshowhistory) {
                    $scope.isdata.filestyle = { "left": (document.documentElement.clientWidth - 448) / 2 + "px" };
                    $scope.isshowhistory = false;   // 文件历史版本显示隐藏
                    $scope.isshowlog = false;   // 文件日志查看显示隐藏
                } else {
                    if (document.documentElement.clientWidth >= 1120) {
                        $scope.isdata.filestyle = { "left": (document.documentElement.clientWidth - 450 - 670) / 2 + "px" };
                    } else {
                        $scope.isdata.filestyle = { "left": "0px" };
                    }
                    $scope.isshowhistory = true;   // 文件历史版本显示隐藏
                    $scope.isshowlog = false;   // 文件日志查看显示隐藏
                }
                $scope.vid = $scope.fileifno.fileversion; //默认主板本


                //$scope.param = { "fileid": "1", "orgid": "0", "userid": "1" };
                $scope.param = { "fileid": $scope.fileifno.upId, "orgid": $scope.fileifno.upOrgId, "userid": $scope.fileifno.upUserId }
                // 获取文件历史版本
                RTS.History_List($scope.param).then(function (data) {
                    $scope.historylist = data.datas;
                })
            }
            $scope.logList = [];
            $scope.logParam = {
                    userid: sysUserInfo.getuserinfo().user_ID,
                    orgid: sysUserInfo.getuserinfo().organization_ID,
                    fileid: $scope.fileifno.upId,
                    startDate: "",
                    endDate: "",
                    type:"",
                    pageIndex: "1",
                    pageSize: "10",
                    pageCount:0    }
            $scope.showlog = function(){
                if ($scope.isshowlog) {
                    $scope.isdata.filestyle = { "left": (document.documentElement.clientWidth - 448) / 2 + "px" };
                    $scope.isshowhistory = false;   // 文件历史版本显示隐藏
                    $scope.isshowlog = false;   // 文件日志查看显示隐藏
                } else {
                    if (document.documentElement.clientWidth >= 1120) {
                        $scope.isdata.filestyle = { "left": (document.documentElement.clientWidth - 450 - 670) / 2 + "px" };
                    } else {
                        $scope.isdata.filestyle = { "left": "0px" };
                    }
                    $scope.isshowhistory = false;   // 文件历史版本显示隐藏
                    $scope.isshowlog = true;   // 文件日志查看显示隐藏
                }
                $scope.vid = $scope.fileifno.fileversion; //默认主板本                                    
                $scope.logParam = {
                    userid: sysUserInfo.getuserinfo().user_ID,
                    orgid: sysUserInfo.getuserinfo().organization_ID,
                    fileid: $scope.fileifno.upId,
                    searchText:"",
                    startDate: "",
                    endDate: "",
                    type:"",
                    pageIndex: "1",
                    pageSize: "10",
                    pageCount:0     }
                // 获取文件历史版本
                RTS.findFileFlowDetailedPage($scope.logParam).then(function (data) {
                    $scope.logList = data.datas;
                    $scope.logParam.pageCount = data.numCount;
                })
            }
            //切换筛选
            $scope.checkType = function (type) {
                $scope.logParam.pageIndex = "1";
                $scope.logParam.type = type;
                // 获取文件历史版本
                RTS.findFileFlowDetailedPage($scope.logParam).then(function (data) {
                    $scope.logList = data.datas;
                    $scope.logParam.pageCount = data.numCount;
                })
            }
            //按名称搜索
            $scope.searchTxt = function () {
                $scope.logParam.pageIndex = "1";
                // 获取文件历史版本
                RTS.findFileFlowDetailedPage($scope.logParam).then(function (data) {
                    $scope.logList = data.datas;
                    $scope.logParam.pageCount = data.numCount;
                })
            }
            $scope.logLoading = false;
            $scope.nextlog=function(){
                if($scope.logLoading){
                    return;                
                }                
                if(($scope.logParam.pageIndex * $scope.logParam.pageSize) > $scope.logParam.pageCount){
                    return;
                }
                $scope.logLoading = true;    
                $scope.logParam.pageIndex = parseInt($scope.logParam.pageIndex)+1;
                // 获取文件历史版本
                RTS.findFileFlowDetailedPage($scope.logParam).then(function (data) {
                    $scope.logLoading = false;    
                    if(data.errorcode =="0")
                    $scope.logList = $scope.logList.concat(data.datas);
                })
            }

            /***********************更新文件开始****************************/
            // 全局上传控件
            $scope.allPlayUpload = function () {
                $scope.UploadParams = { //上传必要的参数
                  obj:this, // angular 对象
                  apply:$scope.$apply,  //文件刷新
                  userobj: sysUserInfo.getuserinfo(),
                  list:$scope.historylist <= 0?[]:$scope.historylist,   //文件列表   
                  fobj:$scope.fileifno,// 文件主表对象 
                  optype: 2,
                  msg:Msg               
                    
                };
                //调用文件上传的 主接口 在主框架中
                allSelectFileObj($scope.UploadParams);
            }
            var fileattributecontroller = $scope.fileuploader = new FileUploader();
            fileattributecontroller.onAfterAddingFile = function (fileItem) {  // 选择文件后 （成功）   0          
                //        console.info('onAfterAddingFile', fileItem);
                if (fileattributecontroller.isUploading) {
                    MsgCon.alert("有文件正在上传。。");
                    return;
                } else {
                    var upfileparam = "?fileobj=" + angular.toJson($scope.fileifno) + "&orgid=" + sysUserInfo.getuserinfo().organization_ID + "&userid=" + sysUserInfo.getuserinfo().user_ID + "&username=" + sysUserInfo.getuserinfo().username;
                    //上传文件路径
                    fileItem.url = RTS.updatafilechild(upfileparam);
                }
            };
            fileattributecontroller.onAfterAddingAll = function (addedFileItems) { // 选择文件后添加到队列   1 
                //        console.info('onAfterAddingAll', addedFileItems);
                if (fileattributecontroller.isUploading) {
                    MsgCon.alert("有文件正在上传。。");
                    return;
                } else {
                    fileattributecontroller.uploadAll();
                }
            };
            // 开始上传
            fileattributecontroller.onBeforeUploadItem = function (item) {    // 2 上传之前一项
                $scope.isbtnload2 = true;
                //        console.info('onBeforeUploadItem', item);
            };
            fileattributecontroller.onProgressItem = function (fileItem, progress) {   // 3 上传进度
                //        console.info('onProgressItem', fileItem, progress);
                //        $scope.exUserList[0].import_Num = progress;    // 上传进度
                //        if (progress == 100) {    // 上传完成后改成处理中
                //            $scope.exUserList[0].import_State = "处理中";
                //        }
            };
            fileattributecontroller.onProgressAll = function (progress) {      //4 队列进度
                //        console.info('onProgressAll', progress);
            };
            fileattributecontroller.onSuccessItem = function (fileItem, response, status, headers) {   // 5上传成功
                //        console.info('onSuccessItem', fileItem, response, status, headers); //fileItem 请求信息 response: 返回值status: 返回状态  headers: 请求头
                $scope.isbtnload2 = false;
                if (response.errorcode == "0") {
                    fileattributecontroller.clearQueue();
                    Msg.success("文件更新成功！")
                    if (response.data != undefined) {
                        $scope.historylist.unshift(response.data);
                        $scope.updateparantobj(response.data);
                    }
                } else {// 上传地址有问题
                    console.log("上传地址有问题:" + response.errorcode);
                }
            };
            fileattributecontroller.onErrorItem = function (fileItem, response, status, headers) {     // 5上传失败
                //        console.info('onErrorItem', fileItem, response, status, headers);
                //        $scope.exUserList[0].import_State = "失败";
                //        MsgCon.alert("连接不上服务器");
                fileattributecontroller.clearQueue();
            };
            fileattributecontroller.onCancelItem = function (fileItem, response, status, headers) {    //5取消上传
                //$scope.exUserList[0].import_State = "取消";
                //        console.info('onCancelItem', fileItem, response, status, headers);
            };
            fileattributecontroller.onCompleteItem = function (fileItem, response, status, headers) {  //6     单文件上传完成
                //        console.info('onCompleteItem', fileItem, response, status, headers);
            };
            fileattributecontroller.onCompleteAll = function () {  // 6 单文件上传完成或者队列上传完成的时候
                //        console.info('onCompleteAll');
                fileattributecontroller.clearQueue();  // 上传完毕清除队列
            };
            /***********************更新文件结束****************************/


            /***************************************文件历史版本开始*****************************************/
            $scope.historylist = [];
            $scope.showid = -1; //要显示的下拉列表框
            $scope.upobj = null; // 传入的子对象
            $scope.vid = -1; //默认主板本
            $scope.showvid = function (id) {  // 显示版本下拉列表
                if ($scope.showid == id) {
                    $scope.showid = -1;
                } else {
                    $scope.showid = id;
                }
            }
            $scope.setvid = function (item, flag) {   //   设置要修改的对子对象
                $scope.showid = -1;
                if (flag == "-1" && item.Edition != $scope.vid) {
                    return;
                }
                if (flag == "-1") { // 自己
                    $scope.vid = -1;
                    $scope.upobj = null;
                } else {
                    $scope.vid = item.Edition;
                    $scope.upobj = item;
                }
            }

            //保存修改版本信息
            $scope.saveversion = function () {
                $scope.isbtnload2 = true;
                if ($scope.upobj == null) {
                    $scope.isbtnload2 = false;
                    Msg.info("设置主版本成功");
                } else {
                    $scope.vsparam = { "filecobj": $scope.upobj, "userid": sysUserInfo.getuserinfo().user_ID, "username": sysUserInfo.getuserinfo().username, "orgid": sysUserInfo.getuserinfo().organization_ID };
                    if ($scope.fileifno.fileversion != $scope.upobj.Edition) {
                        RTS.SetMainVersion($scope.vsparam).then(function (data) {
                            $scope.isbtnload2 = false;
                            if (data.errorcode == 0) {
                                Msg.success("设置主版本成功");
                                $scope.updateparantobj($scope.upobj);           //更新2017-05-10 19:37
                                //$scope.closehistory();
                            } else {
                                Msg.error("设置主版本失败");
                            }
                        }, function callback() {
                            Msg.error("请求数据有误");
                        });
                    }
                }
            }

            //检查数组是否存在
            $scope.containskdList = function (arr, obj) {
                try {
                    var i = arr.length;
                    while (i--) {

                        if (arr[i].id === obj.id) {
                            return i;
                        }
                    }
                    return -1;
                } catch (e) {
                    // statements
                    return -1;
                }
            }
            //删除版本
            $scope.delhistory = function (hisinfo) {
                if ($scope.fileifno.fileversion == hisinfo.Edition) {
                    Msg.info("此记录是主版本");
                    return;
                }
                MsgCon.delnoicon().then(function (flag) {   // 删除弹框
                    if (flag) {
                        $scope.delparam = { "filecid": hisinfo.id, "userid": sysUserInfo.getuserinfo().user_ID, "username": sysUserInfo.getuserinfo().username, "orgid": sysUserInfo.getuserinfo().organization_ID };
                        // 删除文件历史版本
                        RTS.delcfile($scope.delparam).then(function (data) {
                            if (data.errorcode == 0) {
                                Msg.success("删除成功");
                                $scope.historylist.splice($scope.containskdList($scope.historylist, hisinfo), 1);
                            } else {
                                Msg.error("删除失败");
                            }
                        }, function callback() {
                            Msg.error("请求数据有误");
                        });
                    }
                });
            }

             // 关闭文件版本
            $scope.closelog = function () {
                $scope.isshowhistory = false;   // 文件历史版本显示隐藏
                $scope.isshowlog = false;   // 文件日志查看显示隐藏
                $scope.isbtnload2 = false;
                $scope.isdata.filestyle = { "left": (document.documentElement.clientWidth - 448) / 2 + "px" };
            }
            // 关闭文件版本
            $scope.closehistory = function () {
                $scope.isshowhistory = false;   // 文件历史版本显示隐藏
                $scope.isshowlog = false;   // 文件日志查看显示隐藏
                $scope.isbtnload2 = false;
                $scope.isdata.filestyle = { "left": (document.documentElement.clientWidth - 448) / 2 + "px" };
            }

            // 下载
            $scope.play = function (item, index) {
            if(index==1||index=="1"){
                    //                window.open(RTS.downloadfile("?id=" + item.upId + "&type=1"));
                    if (item.fileType== "wxt" || item.fileType== "urls" || item.fileType== "ques") {
                        window.open(RTS.downloadfile2("?id=" + item.upId + "&type=1"));
                    } else {

                        RTS.downloadfile({ id: item.upId, type: index, fileType: item.fileType }).then(function (data) {
                            if (data.errorcode == 0) {
                                if (item.fileType != "wxt" && item.fileType != "urls" && item.fileType != "ques") {
                                    //请求文件服务器
                                    window.open(RTS.filedown("?userid=" + sysUserInfo.getuserinfo().user_ID + "&fileurlonly=" + encodeURI(encodeURI(data.data.fileurlonly)) + "&fileName=" + data.data.upId + "." + data.data.fileType + "&type=" + index));
                                }
                            } else {
                                Msg.error("下载失败");
                            }
                        }, function callback() {
                            Msg.error("请求数据有误");
                        });
                    }
                //子版本下载
                } else {
                     if (item.Extended == "wxt" || item.Extended == "urls" || item.Extended == "ques") {
                            window.open(RTS.downloadfile2("?id=" + item.id + "&type=1"));
                        } else {

                            RTS.downloadfile({ id: item.id, type: index, fileType: item.Extended }).then(function (data) {
                                if (data.errorcode == 0) {
                                    if (item.Extended != "wxt" && item.Extended != "urls" && item.Extended != "ques") {
                                        //请求文件服务器
                                        window.open(RTS.filedown("?userid=" + data.data.upUserId + "&fileurlonly=" + encodeURI(encodeURI(data.data.URL)) + "&fileName=" + data.data.id + "." + data.data.Extended + "&type=" + index));
                                    }
                                } else {
                                    Msg.error("下载失败");
                                }
                            }, function callback() {
                                Msg.error("请求数据有误");
                            });
                        }
                }
            }
            // 关闭
            $scope.ishidefun = function () {
                $scope.addPersonList = [];
                $scope.delPersonList = [];
                $scope.checklist = [];
                $scope.fileifno.fileName = filename;
                filename = "";
                $scope.closehistory();
                $scope.isdata.divhide = false;
                $scope.isbtnload = false;
            }
            // 隐藏
            function documentKeydown(event) {
                if (event.keyCode === 27) {
                    $scope.$apply(function () {
                        $scope.ishidefun();
                    });
                }
            }
            $document.on('keydown', documentKeydown);
            $scope.$on('$destroy', function () {
                $document.off('keydown', documentKeydown);
            });
            var timeo;
            //$scope.controlshow = { "fileattrplay": false, "fileattrdel": false, "fileattrvsion": false };
            /********下载、删除、设置主版本对应的图标的提示文字显示和隐藏****************/
            $scope.showfileMsg = function (biem, filetype) {
                timeo = $timeout(function () {
                    switch (filetype) {
                        case 1: biem.fileattrplay = true; break;
                        case 2: biem.fileattrdel = true; break;
                        case 3: biem.fileattrvsion = true; break;
                        default: break;
                    }
                }, 500);
            }

            $scope.hidefileMsg = function (biem, filetype) {
                $timeout.cancel(timeo);
                switch (filetype) {
                    case 1: biem.fileattrplay = false; break;
                    case 2: biem.fileattrdel = false; break;
                    case 3: biem.fileattrvsion = false; break;
                    default: break;
                }
            }

            //设置主版本
            $scope.setfilemain = function (biem) {
                if ($scope.vid != biem.Edition) {
                    $scope.vid = biem.Edition;
                    $scope.upobj = biem;
                    $scope.saveversion();
                }
            }


            //checkbox全选
            $scope.checkListAll = function () {
                if ($scope.checklist.length == $scope.checkall.length) {
                    $scope.uncheckAll();
                } else {
                    $scope.checklist = angular.copy($scope.checkall);
                }
            }
            //checkbox取消全选
            $scope.uncheckAll = function () {
                $scope.checklist = [];
            };
        }
    };
} ]);


filepreview.directive('onFinishRender', function () {
    return {
        restrict: 'A',
        link: function (scope, element, attr) {

            /*
            if (scope.$last === true) {
            element.ready(function () {
            console.log("1111");
            $("#r_img").remove();
            });
            }
            */

            document.getElementById('fileimg').onload = function (e) {
                if (document.getElementById('fileimg').src != "") {
                    e.stopPropagation();
                    console.log(1);
                    document.getElementById("r_img").outerHTML = '';
                    /*
                    如果要获取图片的真实的宽度和高度有三点必须注意
                    1、需要创建一个image对象：如这里的$("<img/>")
                    2、指定图片的src路径
                    3、一定要在图片加载完成后执行如.load()函数里执行
                    */
                    var realWidth = this.width;
                    var realHeight = this.height;
                    //如果真实的宽度大于浏览器的宽度就按照100%显示
                    if (realWidth > realHeight) {
                        if (parseFloat(realHeight / realWidth).toFixed(2) > 0.75) {
                            $("#fileimg").css("margin", "auto 0");
                        } else {
                            $("#fileimg").css("margin", "0 auto");
                        }
                    } else {//如果小于浏览器的宽度按照原尺寸显示                        
                        $("#fileimg").css("margin", "auto 0");
                    }
                } else {
                    console.log(2);
                    document.getElementById("r_img").outerHTML = '';
                }
            }
        }


    }
});
